﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using TableProto;

public class MainItemChild : MonoBehaviour, IPointerClickHandler {

    public GameObject GrayObj;
    public GameObject BuyObj;
    public GameObject DownloadObj;
    public Image DownloadingObj;
    public Image NewTipsObj;

    public Text NameText;
    public Image DownloadingProImage;
    public Text DownloadProgressText;
    public GameObject UpdateTextObj;

    public Image image;

    private MainItemInfo info;

    private bool isbuy;
    private ModuleAssetState state;
    private int curId;

    private string precent = "%";

    public void Init(MainItemInfo inf)
    {
        this.info = inf;
        this.curId = (int)inf.id;
        image.sprite = UISpriteManager.Instance.GetSprite(emUIAltas.Main, inf.image);
        NameText.text = inf.name;

        RemoveHandler();
        EventBus.Instance.AddEventHandler(EventID.PAY_BUY_SUC, this.OnPaySuc);
        EventBus.Instance.AddEventHandler(EventID.MAIN_STATE_ENTER, RefreshTipProgress);

        ReflashState();
        RefreshTipProgress();
#if LOCAL_RELEASE
#else
        GrayObj.SetActive(false);
#endif
    }

    private void RemoveHandler()
    {
        EventBus.Instance.RemoveEventHandler<int, float>(EventID.MODULE_PROGRESS_CHANGE, this.ChangeProgress);
        EventBus.Instance.RemoveEventHandler<int, long>(EventID.MODULE_UNZIP_DONE, this.DownloadDone);
        EventBus.Instance.RemoveEventHandler<int>(EventID.MODULE_DOWNLOAD_ERROR, this.DownloadError);
        EventBus.Instance.RemoveEventHandler(EventID.PAY_BUY_SUC, this.OnPaySuc);
        EventBus.Instance.RemoveEventHandler(EventID.MAIN_STATE_ENTER, RefreshTipProgress);
    }

    private void OnPaySuc()
    {
        ReflashState();
    }

    private void ReflashState()
    {
        isbuy = this.info.main_buy == 0 || PayManager.Instance.IsBuyItem(curId);
        if (isbuy)
        {
            ReflashDownloadState();
        }
        else
        {
            GrayObj.SetActive(true);
            BuyObj.SetActive(true);
        }
    }

    private void RefreshTipProgress()
    {
        NewTipsObj.gameObject.SetActive(false);
        if (info != null && info.newtips == 1)
        {
            MainTipInfo tipInfo = LocalDataManager.Instance.Load<MainTipInfo>();
            NewTipsObj.gameObject.SetActive(!tipInfo.itemList.Contains(info.id));
        }
    }

    private void SaveTipProgress()
    {
        if (info != null)
        {
            MainTipInfo tipInfo = LocalDataManager.Instance.Load<MainTipInfo>();
            if (!tipInfo.itemList.Contains(info.id))
            {
                tipInfo.itemList.Add(info.id);
            }
            LocalDataManager.Instance.Save<MainTipInfo>(tipInfo);
        }
    }

    private void ReflashDownloadState()
    {
        DownloadObj.SetActive(false);
        DownloadingObj.gameObject.SetActive(false);
        state = ModuleAssetManager.Instance.GetAssetState(curId);
        if (state == ModuleAssetState.Downloaded)
        {
            GrayObj.SetActive(false);
            //NameText.gameObject.SetActive(true);
        }
        else if (state == ModuleAssetState.Downloading)
        {
            GrayObj.SetActive(true);
            //NameText.gameObject.SetActive(false);
            StartDownload();
        }
        else if (state == ModuleAssetState.NoDownload)
        {
            GrayObj.SetActive(true);
            DownloadObj.SetActive(true);
            UpdateTextObj.SetActive(false);
            //NameText.gameObject.SetActive(true);
        }
        else if (state == ModuleAssetState.NeedUpdate)
        {
            GrayObj.SetActive(true);
            DownloadObj.SetActive(true);
            UpdateTextObj.SetActive(true);
            //NameText.gameObject.SetActive(true);
        }
    }

    private void ChangeProgress(int id, float p)
    {
        Debug.Log("-------------- ChangeProgress!  id: " + id + "  progress: " + p); ;
        if (id == this.curId)
        {
            DownloadingProImage.fillAmount = p;
            DownloadProgressText.text = (int)(p * 100) + precent;
        }
    }

    private void DownloadDone(int id, long allSize)
    {
        Debug.Log("-------------- DownloadDone!  id: " + id);
        if (id == curId)
        {
            GrayObj.SetActive(false);
        }
    }

    private void DownloadError(int id)
    {
        Debug.Log("-------------- DownloadError!  id: " + id);
        if (id == curId)
        {
            GrayObj.SetActive(true);
            DownloadObj.SetActive(true);
            NameText.gameObject.SetActive(true);

            DownloadingObj.gameObject.SetActive(false);
            UpdateTextObj.SetActive(false);
            DownloadProgressText.text = "";
        }
    }

    public void OnPointerClick(PointerEventData eventData)
    {
#if LOCAL_RELEASE
        state = ModuleAssetManager.Instance.GetAssetState(curId);
        Debug.LogError(state);
        if (!isbuy)
        {
            Debug.Log("---------- 请求购买");
            //购买
            UnlockGiftBagController.Instance.OpenView(() => {
                PayManager.Instance.Pay(curId, (id, suc) => {
                    Debug.Log(id + "," + suc + "," + curId);
                    if (id == curId && suc)
                    {
                        BuyObj.SetActive(false);
                        ReflashState();
                    }
                });
            });
        }
        else
        {
            Debug.Log("---------- 检测下载状态");
            if (state == ModuleAssetState.Downloaded)
            {
                HUIEventManager.Instance.DispatchUIEvent(enUIEventID.Main_Btn_Item_Child_Click, new stUIEventParams()
                {
                    argInt = curId,
                });
                DownloadItemManager.Instance.ReflashUseTime(curId);
                ModuleAssetManager.Instance.VersionCheck(curId);
                SaveTipProgress();
            }
            else if (state == ModuleAssetState.Downloading)
            {
                //点击没效果
                Debug.Log("---------- 已经下载");
            }
            else if (state == ModuleAssetState.NoDownload || state == ModuleAssetState.NeedUpdate)
            {
                Debug.Log("---------- 请求下载");
                DownloadObj.SetActive(false);
                StartDownload();
                ModuleAssetManager.Instance.StartDownload(curId);
            }
        }
#else
        HUIEventManager.Instance.DispatchUIEvent(enUIEventID.Main_Btn_Item_Child_Click, new stUIEventParams()
        {
            argInt = curId,
        });
        SaveTipProgress();
#endif
    }

    private void StartDownload()
    {
        DownloadingObj.gameObject.SetActive(true);
        DownloadingProImage.fillAmount = 0f;
        DownloadProgressText.text = "0%";
        RemoveHandler();
        EventBus.Instance.AddEventHandler<int, float>(EventID.MODULE_PROGRESS_CHANGE, this.ChangeProgress);
        EventBus.Instance.AddEventHandler<int, long>(EventID.MODULE_UNZIP_DONE, this.DownloadDone);
        EventBus.Instance.AddEventHandler<int>(EventID.MODULE_DOWNLOAD_ERROR, this.DownloadError);
    }

    private void OnDestroy()
    {
        RemoveHandler();
    }


}
